package com.lib.torment.androidlib.adapter;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.util.SparseArray;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.util.List;

/**
 * 拥有多布局显示的功能<br/>
 * 使用这个布局的数据源必须继承 MultiItemEntity，并且设置它的itemType，用于提供不同类型的布局支持<br/>
 * Created by Torment on 16-7-15.
 */
public abstract class MultiItemAppAdapter<T extends MultiItemEntity> extends RefreshAppAdapter<T> {
    private SparseArray<Integer> layouts = new SparseArray<>();

    private static final int DEFAULT_VIEW_TYPE = -0xff;

    public MultiItemAppAdapter(Context context, List<T> data) {
        super(context, 0, data);
    }

    @Override
    protected int getDefItemViewType(int position) {
        Object item = mData.get(position);
        if (item != null) {
            return ((MultiItemEntity) item).getItemType();
        }
        return DEFAULT_VIEW_TYPE;
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        return createBaseViewHolder(parent, getLayoutId(viewType));
    }

    private int getLayoutId(int viewType) {
        return layouts.get(viewType);
    }

    protected void addItemType(int type, @LayoutRes int layoutResId) {
        if (layouts == null) {
            layouts = new SparseArray<>();
        }
        layouts.put(type, layoutResId);
    }
}
